/**
 * @description convert link elem to link-card
 * @author Ling
 * @date 2024-08-08
 */

import { IDomEditor, DomEditor, t, SlateNode, SlateTransforms, SlateEditor } from '@wangeditor/editor';
import { IButtonMenu } from '@wangeditor/editor';
import { LinkCardElement } from '../../custom-types';
import { LINK_CARD_ICON_SVG } from '../../icon-svg';

class ConvertLinkCardToLink implements IButtonMenu {
  readonly title = '转成普通链接';
  readonly iconSvg = LINK_CARD_ICON_SVG; // 无 icon
  readonly tag = 'button';

  private getSelectedLinkElem(editor: IDomEditor): LinkCardElement | null {
    const node = DomEditor.getSelectedNodeByType(editor, 'link-card');
    if (node == null) return null;
    return node as LinkCardElement;
  }

  getValue(editor: IDomEditor): string | boolean {
    return '';
  }

  isActive(editor: IDomEditor): boolean {
    // 无需 active
    return false;
  }

  isDisabled(editor: IDomEditor): boolean {
    if (editor.selection == null) return true;

    const linkElem = this.getSelectedLinkElem(editor);
    if (linkElem == null) {
      // 选区未处于 link node ，则禁用
      return true;
    }
    return false;
  }

  async exec(editor: IDomEditor, value: string | boolean) {
    if (this.isDisabled(editor)) return;

    const linkElem = this.getSelectedLinkElem(editor);
    if (linkElem == null) return;
    let { link, linkType, target, title, articleId } = linkElem;
    console.log('卡片链接转链接：', linkElem);
    if (!linkType && target) {
      // 截取target进行拆分赋值
      articleId = target.split('_')[1];
      linkType = target.split('_')[0];
    }

    try {
      const linkPath = DomEditor.findPath(editor, linkElem);

      SlateTransforms.removeNodes(editor, { at: linkPath });
      SlateTransforms.splitNodes(editor, { always: true });
      // 焦点前移一位
      editor.move(-1);
      // 插入链接
      const linkNode = { type: 'link', url: link, target, linkType, articleId, children: [{ text: title }] };
      SlateTransforms.insertNodes(editor, linkNode);
    } catch (err) {
      console.error('Convert to link error', err);
    }
  }
}

export default ConvertLinkCardToLink;
